/* -----------------
* brief
* 1. this is code gen by tools
 */

package service

import (
	"errors"
	"github.com/mjiulee/lego"
	"saas_sys_base/common"
	. "saas_sys_base/modules/tenant/models"
)

type TenantMemberService struct {
	// add your model here
	tbTenantMember TenantMember
}

func (t *TenantMemberService) ListTenantMember(keyword string, page, psize int) ([]map[string]string, int64, error) {
	// 业务查询
	queryMap := map[string]interface{}{
		"table":  map[string]string{"table": "tb_tenant_member", "alias": "t1"},
		"fields": []string{"t1.*"},
		"join":   []map[string]string{
			// map[string]string{"table": "tb_xx as t2", "on": "t2.xid = t1.id"},
		},
		"where": []lego.QMapWhereField{
			//{"t1.if_del", "=", 0, "AND", false},
		},
		"search": map[string]string{
			//"t1.id": req.Keyword,
		},
		"orders": []string{"t1.id asc"},
		"page": map[string]int{
			"page":  page,
			"psize": psize,
		},
	}
	return lego.QueryListByMap(queryMap)
}

/* 根据id获取记录
 * -----------------
 */
func (t *TenantMemberService) GetTenantMemberById(id int64) *TenantMember {
	return t.tbTenantMember.RecodeById(id)
}

/* 添加
 * -----------------
 */
func (t *TenantMemberService) SaveTenantMember(item2add *TenantMember) bool {
	return t.tbTenantMember.AddRecode(item2add)
}

/* 删除(硬删除)*/
func (t *TenantMemberService) DelTenantMemberById(id int64) bool {
	return t.tbTenantMember.DelRecodeById(id)
}

/* 更新
 * -----------------*/
func (t *TenantMemberService) UpdateTenantMember(rc *TenantMember) bool {
	return t.tbTenantMember.UpdateRecode(rc)
}

//自定义函数
func (t *TenantMemberService) AddTenantMember(tid int64, uid int64) error {
	rc := t.tbTenantMember.RecodeByTidAndUid(tid, uid)
	if rc == nil {
		//已经加过的成员，直接返回
		return nil
	}

	item2add := new(TenantMember)
	item2add.TenantId = tid
	item2add.Uid = uid
	item2add.State = common.STATE_YES
	isErr := t.tbTenantMember.AddRecode(item2add)
	if isErr {
		return errors.New("AddTenantMember failed")
	}
	return nil
}

/*
Uid对应的用户是否具备对应租户的权限
*/
func (t *TenantMemberService) HasPermissionInTenant(tid int64, uid int64) bool {
	rc := t.tbTenantMember.RecodeByTidAndUid(tid, uid)
	if rc == nil {
		return false //无权限
	}

	if rc.State != common.STATE_YES {
		return false //无权限
	}

	return true
}

func (t *TenantMemberService) GetTenantMemberByUidAndRole(uid int64, role TENANT_ROLE) *TenantMember  {
	rc := t.tbTenantMember.RecodeByUidAndRole(uid, role)
	return rc
}

func (t *TenantMemberService) ListTenantByMemberUid(uid int64) ([]*Tenant, int64, error) {
	tenantList, total, err := t.tbTenantMember.ListTenantByMemberUid(uid)
	return tenantList, total, err
}